<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '消息',
  },
}
</route>
<template>
  <!--  :style="{ height: height }" -->
  <view class="overflow-hidden" style="height: 100vh">
    <view class="tabbar" style="zindex: 100">
      <wd-navbar title="消息列表" :bordered="false">
        <template #right>
          <!-- <div class="title_box flex">
            <view class="title flex-1">消息列表</view> -->
          <view class="beread" @click="beReadAll"></view>
          <!-- </div> -->
        </template>
      </wd-navbar>

      <view class="cu-bar search-container" style="width: 100vw">
        <cusPicker
          label=""
          label-width="0%"
          v-model="checkvalue"
          :columns="cateList"
          value-key="key"
          label-key="value"
          :column-change="columnChange"
          @confirm="handleConfirm"
          use-default-slot
          :key="key"
          style="color: #fff; padding-left: 10rpx"
        >
          {{ checkValueName }}
        </cusPicker>
        <wd-search
          placeholder="请输入内容"
          style="flex: 1; margin-top: 4rpx; background: initial"
          hideCancel
          v-model="params.content"
          @search="searchHandle"
        ></wd-search>

        <button
          @click="searchHandle"
          class="cu-btn bg-gradual-green shadow-blur round"
          style="margin-right: 10rpx"
        >
          查询
        </button>
      </view>
      <view class="tabs">
        <view
          v-for="(item, index) in tableList"
          :class="['item', 'i' + index, item.value === activeTab ? 'on' : '']"
          :key="item.value"
          @click="onTabChange(item.value)"
        >
          {{ item.name }}
        </view>
      </view>
    </view>
    <view class="msg-box" :style="{ paddingTop: padTop }">
      <view class="msg" :style="{ height: msgH }">
        <view class="body">
          <scroll-view
            scroll-y
            :style="{ height: msgH }"
            refresher-enabled
            :refresher-threshold="80"
            :refresher-triggered="triggered"
            refresher-background="#f1f1f1"
            @scrolltolower="onReachLower"
            @refresherrefresh="onRefresh"
            @refresherrestore="onPullStore"
          >
            <view
              class="message"
              v-for="(msg, index) in msgList"
              @click="toPage(msg, index)"
              :key="index"
              :class="msg.readFlag == 0 ? 'unread' : ''"
            >
              <view class="title">
                <text class="t">{{ msg.title }}</text>
                <!-- <text class="date">{{$ago(msg.senderDate)}}</text> -->
                <text class="date">{{ formatTime(msg.createTime) }}</text>
              </view>
              <!-- <view
            v-if="msg.messageType === 'text' || msg.messageType === null"
            class="content"
            @click.stop="mark(msg)"
          >
            {{ msg.content }}
          </view> -->
              <!-- <view v-else-if="msg.messageType === 'pic'" class="content">
            <view>点击查看图片</view>
            <view></view>
          </view> -->
              <view class="content">
                <view>{{ msg.content }}</view>
                <view></view>
              </view>
            </view>
            <view v-if="!msgList.length && !inFreshing" class="no-msg">暂无消息</view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>
<script lang="ts" setup>
import { getNotices, setRead, setReadAll, getNoticesTab, getCateList } from '@/service/message';
// #ifdef APP-PLUS
import setBedge from '@/utils/set_badge';
// #endif
import showModal from '@/utils/modal';
import cusPicker from '@/pages/index/components/cusPicker.vue';
const inFreshing = ref(false);
const haveMore = ref(false);
const tabs = ref([]);
const tabCur = ref(0);
const params = reactive({
  current: 1,
  size: 20,
  clientType: 1,
  category: '',
  module: '',
  content: '',
  readFlag: '0',
});
let key = ref(+new Date());
onShow(() => {
  // nextTick(() => {
  //   triggered.value = true;
  // });
  // #ifdef APP-PLUS
  setBedge();
  // #endif

  getCategory();
});
onLoad(() => {
  nextTick(() => {
         triggered.value = true;
       });
});
const category = ref('');
const totalCount = ref(0);
const cateList = ref([]);
const checkvalue = ref([]);
const checkValueName = ref('全部');
const getCategory = () => {
  getCateList({ category: category.value }).then((res) => {
    if (res.code == 0) {
      cateList.value = [res.data];
    }
  });
};
const tableList = ref([
  {
    value: '0',
    name: '未读',
  },
  {
    value: '1',
    name: '已读',
  },
  {
    value: '',
    name: '全部',
  },
]);
const activeTab = ref('0');
const onTabChange = (e) => {
  activeTab.value = e;
  params.current = 1;
  params.readFlag = e;
  getNoticesList('refresh');
};
const { proxy } = getCurrentInstance();
const msgList = ref([]);
const triggered = ref<any>(false);
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
const height = `calc(100vh - 55px)`;
const upx2px = (num) => {
  return uni.upx2px(num);
};
const tHeight = ref(130);
nextTick(() => {
  let info = uni.createSelectorQuery().in(proxy).select('.tabbar');
  info
    .boundingClientRect((data) => {
      // data - 包含元素的高度等信息
      console.log(data, 12312321); // 获取元素宽度
      tHeight.value = data.height;
    })
    .exec();
});

const padTop = ref(((safeAreaInsets?.top || 0) +  tHeight.value) + 'px');
const msgH = ref(`calc(100vh - (${(safeAreaInsets?.top || 0) + tHeight.value}px)`);
// const msgH1 = ref(`calc(100vh - (${(safeAreaInsets?.top || 0) + tHeight.value}px)`);
// const bheight = ref(`calc(100vh - (${safeAreaInsets?.top || 0 + 80}px)`);
const getNoticesList = (event) => {
  if (params.current == 1) {
    haveMore.value = true;
  }
  if (inFreshing.value) return;
  if (!haveMore.value) return;
  inFreshing.value = true;
  haveMore.value = false;

  if (event) {
    msgList.value = [];
  }
  getNotices(params)
    .then((res) => {
      triggered.value = false;
      inFreshing.value = false;
      if (res.code === 0) {
        msgList.value.push(...res.data.records);
        if (res.data.records.length >= params.size) {
          params.current += 1;
          haveMore.value = true;
        } else {
          haveMore.value = false;
        }
      }
    })
    .catch((err) => {
      triggered.value = false;
      inFreshing.value = false;
      haveMore.value = false;
    });
};
const searchHandle = (e) => {
  // cinvcode.value = e.value;
  // params.title = e.value;
  params.current = 1;
  getNoticesList(true);
};

const columnChange = ({ selectedItem, resolve, finish }) => {
  setTimeout(() => {
    if (selectedItem.children && selectedItem.children.length) {
      resolve(selectedItem.children);
    } else {
      // 没有下一项时，执行完成
      finish();
    }
  }, 300);
};

const handleConfirm = (e) => {
  const value = e.value;
  const selectedItems = e.selectedItems;
  checkvalue.value = e.value || [];

  if (selectedItems && selectedItems.length) {
    if (selectedItems[selectedItems.length - 1]['value']) {
      checkValueName.value = selectedItems[selectedItems.length - 1]['value'];
    }
    if (value && value.length == 1) {
      params.module = value[value.length - 1];
      params.category = '';
    } else if (value && value.length == 2) {
      params.category = value[value.length - 1];
      params.module = value[value.length - 2];
    }
  } else {
    checkValueName.value = '全部';
    params.category = '';
    params.module = '';
  }
  // cinvccode.value = value[value.length - 1];
  params.current = 1;
  getNoticesList(true);
};
const onReachLower = () => {
  if (haveMore.value) {
    getNoticesList('');
  }
};
const beReadAll = () => {
  showModal({
    title: '提示',
    content: '确定把全部未读消息标记为已读?',
    showCancel: true,
  }).then(() => {
    setReadAll().then((res) => {
      if (res.code !== 0) return;
      uni.showToast({
        title: '标记成功',
        icon: 'none',
      });
      // #ifdef APP-PLUS
      plus.runtime.setBadgeNumber(-1);
      plus.runtime.setBadgeNumber(0);
      uni.removeTabBarBadge({
        index: 1,
      });
      //  #endif
      getNoticesList('refresh');
    });
  });
};
const formatTime = (time) => {
  return time.substring(0, 10);
};
const onRefresh = () => {
  params.current = 1;
  getNoticesList('refresh');
};
const onPullStore = () => {
  triggered.value = 'restore';
};
const isClicking = ref(false);
const toPage = (msg, index) => {
  try {
    setRead(msg.id);
  } catch (error) {
    console.log();
  }
  if (isClicking.value) return;
  isClicking.value = true;
  if (msg.readFlag === 0) {
    msg.readFlag = 1;
  }

  // #ifdef APP-PLUS
  setTimeout(() => {
    setBedge();
  }, 200);

  // #endif
  if (msg.appRoute) {
    let rou = msg.appRoute;
    const queryInfo = rou?.split('?').length > 1 ? rou?.split('?')[1] : '';

    // nextTick(() => {
    const arr = queryInfo.split('&');
    const obj = { _source: 'message' };
    arr.map((item) => {
      const a = item.split('=');
      obj[a[0]] = a[1];
      return item;
    });
    const path = rou?.split('?')[0];
    if (
      obj &&
      (obj.cusFlag == 3 || obj.cusFlg == 3) &&
      (path == '/pages/pm/requirement/form' || path == '/pages/pm/requirement/detail')
    ) {
      if (path == '/pages/pm/requirement/detail') {
        rou = rou.replace('/requirement/detail', '/gongying/form');
        rou += rou.indexOf('&review') >= 0 ? '' : '&review=1';
      } else {
        rou = rou.replace('/requirement/form', '/gongying/form');
      }
    }

    uni.navigateTo({
      url: `${rou}`,
      complete: () => {
        isClicking.value = false;
      },
    });
    if (msg.readFlag == 0) {
      // msg.readFlag = 1;
      msgList.value.splice(index, 1);
    }
  } else {
    if (msg.readFlag == 0) {
      // msg.readFlag = 1;
      msgList.value.splice(index, 1);
    }
    // setTimeout(() => {
    //   params.current = 1;
    //   getNoticesList('refresh');
    //   isClicking.value = false;
    // }, 300);
  }
};
</script>
<style lang="scss" scoped>
uni-page-body {
  overflow-y: hidden;
}

.search-container .action .cu-btn {
  padding: 0 24rpx;
}

.bg-gradual-green {
  color: #fff;
  background-image: linear-gradient(45deg, #39b54a, #8dc63f);
}

.cu-btn {
  position: relative;
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 64rpx;
  padding: 0 30rpx;
  margin-right: initial;
  margin-left: initial;
  overflow: visible;
  font-size: 28rpx;
  line-height: 1;
  text-align: center;
  text-decoration: none;
  border: 0;
  transform: translate(0, 0);
}
.tabbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: linear-gradient(45deg, #0081ff, #1ab3f5);
  z-index: 100;
}
.cu-bar {
  display: flex;
  position: relative;
  align-items: center;
  min-height: 100rpx;
  justify-content: space-between;
}
.cu-bar .action:last-child {
  margin-right: 30rpx;
}
.cu-bar .action:first-child {
  margin-left: 30rpx;
  font-size: 30rpx;
}
.msg-box {
  display: flex;
  flex: 1;
  overflow: auto;
  // height: 100%;
  font-size: 28rpx;
  padding-top: 120rpx;
  background: #f7f7f7;
  // height:calc(100vh - 200rpx - 100rpx - env(safe-area-inset-bottom));
  .nav {
    width: 170rpx;
    min-width: 170rpx;
    background: #fff;
    white-space: initial;
    &uni-scroll-view {
      flex: unset;
    }
    .uni-scroll-view {
      width: 170rpx;
    }
    .cu-item {
      // width: 100%;
      text-align: center;
      background-color: #fff;
      margin: 0;
      border: none;
      padding: 0 10rpx !important;
      height: 120rpx;
      line-height: 120rpx;
      position: relative;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      &.badge::after {
        content: '';
        position: absolute;
        width: 14rpx;
        height: 14rpx;
        background: #ff6274;
        border-radius: 50%;
        z-index: 99;
        right: 15rpx;
        top: 30rpx;
      }
      &.cur {
        background-color: #f1f1f1;
      }
      &.cur::after {
        content: '';
        width: 8rpx;
        height: 30rpx;
        border-radius: 10upx 0 0 10rpx;
        position: absolute;
        background-color: currentColor;
        top: 0;
        right: 0upx;
        bottom: 0;
        margin: auto;
      }
    }
  }
  .msg {
    flex: 1;
    padding: 10rpx 10rpx 0rpx;
    max-width: 100vw;
    // max-width: calc(100vw - 200rpx);
    .action {
      display: flex;
      justify-content: space-between;
    }
    .action.topic {
      width: 100%;
      .module {
        font-weight: bold;
      }
    }
    .body {
      height: 100%;
      // height: calc(100% - 100rpx);
      background-color: rgb(241, 241, 241);
      scroll-view {
        height: 100%;
        // height: calc(100% - 150rpx);
        .message {
          padding: 10rpx 20rpx 20rpx 20rpx;
          background: #fff;
          margin-top: 10rpx;
          position: relative;
        }
        .message.unread::after {
          content: '';
          width: 14rpx;
          height: 14rpx;
          background-color: #ff6274;
          border-radius: 50%;
          position: absolute;
          right: 10rpx;
          top: 10rpx;
          z-index: 10;
        }
        .message .title {
          display: flex;
          padding-top: 15rpx;
          line-height: 40rpx;
        }
        .message .title .t {
          flex: 1;
          // font-weight: 600;
          font-size: 28rpx;
        }
        .message .date {
          width: 190rpx;
          float: right;
          font-size: 0.8125rem;
          color: #8a8a8a;
          text-align: right;
        }
        .message .content {
          text-align: justify;
          padding: 15rpx 0;
          word-break: break-all;
          color: #515151;
        }
      }
    }
  }
}
// .uni-scroll-view-content {
//   height: calc(100% - 150rpx);
// }
.beread {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
  background: url(../../static/beread.png) no-repeat;
  background-size: 50rpx 50rpx;
}
:deep(.wd-navbar__left--hover) {
  background: none;
}
.no-msg {
  text-align: center;
  padding: 40px 0;
}

:deep(.wd-navbar__right--hover) {
  background: none;
}

.tabs {
  display: flex;
  justify-content: space-between;
  padding: 0 30rpx;
  // margin-top: 15rpx;

  .item {
    position: relative;
    padding: 15rpx 0;
    font-size: 30rpx;
    color: #fff;
    text-align: center;
    opacity: 0.5;
    transition: all 0.3s;

    &.on {
      opacity: 1;

      &::after {
        position: absolute;
        bottom: -8rpx;
        left: 50%;
        width: 12rpx;
        height: 12rpx;
        content: '';
        background: #f1f1f1;
        border-radius: 50%;
        transform: translate(-50%);
      }
    }
  }
}
</style>
